<?php
namespace App\Controllers\Sms;

use App\Controllers\BaseController;
use App\Library\App;
use App\Library\Helper;
use App\Models\Receipt;

class ReceiptController extends BaseController {

    public function initialize() {
        parent::initialize();
    }

    public function yunpianAction() {
        $retMo = file_get_contents('php://input');
        //App::Logger()->debug('yp=' . urldecode($retMo));
        //$retMo = 'sms_status=%5B%7B%22sid%22%3A5212337672%2C%22uid%22%3Anull%2C%22user_receive_time%22%3A%222016-03-08+10%3A46%3A31%22%2C%22error_msg%22%3A%22DELIVRD%22%2C%22mobile%22%3A%2213656874499%22%2C%22report_status%22%3A%22SUCCESS%22%7D%5D';
        if(strpos($retMo, 'sms_status=') === false) {
            echo '0';
            exit();
        }
        $retMo   = substr($retMo, 11);
        $retMo   = urldecode(urldecode($retMo));
        $moArray = json_decode($retMo, true);
        if(is_array($moArray) && isset($moArray[0]) && isset($moArray[0]['mobile'])) {
            $gatewayMsg = http_build_query($moArray[0]);
            $gatewayMsg = mb_strlen($gatewayMsg, 'utf-8') > 600 ? mb_substr($gatewayMsg, 0, 600) : $gatewayMsg;
            $data       = [
                'mobile'      => $moArray[0]['mobile'],
                'status'      => isset($moArray[0]['report_status']) && $moArray[0]['report_status'] == 'SUCCESS' ? 1 : 0,
                'receive_at'  => isset($moArray[0]['user_receive_time']) ? $moArray[0]['user_receive_time'] : Helper::getNow(),
                'gateway'     => 'yunpian',
                'gateway_msg' => $gatewayMsg,
                'create_at'   => Helper::getNow()
            ];
            //插入数据库mt_receipt_log
            $receipt = new Receipt();
            $receipt->add($data);
            echo 0;
            exit();
        }
    }

    public function chanzorAction() {
        $retMo = file_get_contents('php://input');
        //App::Logger()->debug('chanzor=' . $retMo);
        $moArray = json_decode(json_encode((array)simplexml_load_string($retMo)), true);;
        $receipt = new Receipt();
        if(is_array($moArray)) {
            foreach($moArray['statusbox'] as $v) {
                $gatewayMsg = urldecode(http_build_query($v));
                $gatewayMsg = mb_strlen($gatewayMsg, 'utf-8') > 600 ? mb_substr($gatewayMsg, 0, 600) : $gatewayMsg;
                $data       = [
                    'mobile'      => $v['mobile'],
                    'status'      => $v['status'] == 10 ? 1 : 0,
                    'receive_at'  => $v['receivetime'] ? $v['receivetime'] : Helper::getNow(),
                    'gateway'     => 'chanzor',
                    'gateway_msg' => $gatewayMsg,
                    'create_at'   => Helper::getNow()
                ];
                $receipt->add($data);
            }
        }
        echo 0;
        exit();
    }

    public function daredoAction() {
    }
}
